from flask import current_app,render_template, jsonify, request, g

from info.utils.commony import user_login_data
from info.models import User, News, Category
from info.utils.response_code import RET
from . import index_blu

@index_blu.route('/')
@user_login_data
def index():
    user = g.user


    try:
        # 点击排行
        from info import constants
        news_click = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    try:
        news_category = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)


    data = {
        "user_info": user.to_dict() if user else None,
        "news_click": news_click,
        "news_category":news_category
    }
    return render_template("news/index.html", data=data)

@index_blu.route("/favicon.ico")
def get_web_ico():
    """favicon.ico图标处理"""
    return current_app.send_static_file("news/favicon.ico")

@index_blu.route("/news_list")
def news_list():
    # 思路分析(步骤)：
    # 1、获取参数，前端发送通过GET参数发送
    data_dict = request.args
    page= data_dict.get('page',1)
    cid= data_dict.get('cid',1)
    per_page= data_dict.get('per_page',5)
    try:
        page = int(page)
        cid = int(cid)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    filters = []
    if cid != 1:
        filters.append(News.category_id == cid)
    # 2、分页查询新闻表中的新闻(根据分类id，即cid；降序；使用分页查询；查询到的是python的模型对象列表)
    try:
        # *filters解包相当于没有添加到列表
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
        items = paginate.items  # 查询到的第page页的数据(其实是python的模型对象列表)
        totalPage = paginate.pages
        currentPage = paginate.page
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")
    # 3. 返回数据之前需要把每一个模型对象转换成字典格式，因为js不认识python的模型对象
    newsList = []
    for news in items:
        newsList.append(news.to_basic_dict())

    # ４. 返回结果
    return jsonify(errno=RET.OK, errmsg="OK", newsList=newsList,totalPage=totalPage,currentPage=currentPage)
